package gat.common.util;

import cn.hutool.core.date.DateTime;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.model.ObjectMetadata;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.StorageClass;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.InputStream;
import java.util.UUID;

/**
 * @Author：liucaihong
 * @date：2024/3/7 10:24
 * @description:
 */
@Slf4j
@Component
public class CosUtil {

    @Resource
    private CosConfig cosConfig;


    public String uploadFile(MultipartFile file){
        COSClient cosClient = cosConfig.getCOSClient();
        try {
            String originalfileName = file.getOriginalFilename();
            InputStream inputStream = file.getInputStream();
            String key = getFileKey(originalfileName);
            ObjectMetadata objectMetadata = new ObjectMetadata();
            PutObjectRequest putObjectRequest = new PutObjectRequest(cosConfig.getBucketName(), key, inputStream, objectMetadata);

            putObjectRequest.setStorageClass(StorageClass.Standard_IA);
            cosClient.putObject(putObjectRequest);

            return cosConfig.getUrl() + key;

        } catch (Exception e) {
            log.error("上传文件报错:"+e.getMessage(),e);
        }finally {
            cosClient.shutdown();

        }
        return null;
    }


    /**
     * 生成文件路径
     *
     * @return
     */
    private String getFileKey(String originalfileName) {
        String filePath = cosConfig.getFolder();
        String fileType = originalfileName.substring(originalfileName.lastIndexOf("."));
        String replace = UUID.randomUUID().toString().replace("-", "");
        filePath =  filePath  + "/" + new DateTime().toString("yyyyMMdd") + "/" + replace + fileType;
        return filePath;
    }

}
